#!/usr/bin/python
import commonLib
import os
from time import sleep

#Simple script that runs the programs one by one 
#and does a few checking and basic tasks

#I write my PID in a file so easy it's easy to kill me
serial = int(commonLib.getOptions()['serial'])

f = open("./../webserverScripts/pid"+str(serial),'a')
f.write (' '+str(os.getpid())+' ')
f.close()

line = ""

if os.path.isdir('anchorPoint'+str(serial)):
	f = open('anchorPoint'+str(serial),'r')
	line = f.readline()
	f.close()

if line == "": #Ugly way to do it but fast coded...
	pid = os.spawnvpe(os.P_NOWAIT, 'python',[ 'python', './findDependencies.py',str(serial)],os.environ)
	f = open("./../webserverScripts/pid"+str(serial),'a')
	f.write (' '+str(pid)+' ')
	f.close()

	os.wait()

	f=open('anchorPoint'+str(serial),'w')
        f.write("assess")
	f.close()
	line = "assess"

if line.find("assess") != -1:
	pid =os.spawnvpe(os.P_NOWAIT, 'python',[ 'python', './assessInitCalls.py' ,str(serial)],os.environ)

	f = open("./../webserverScripts/pid"+str(serial),'a')
	f.write (' '+str(pid)+' ')
	f.close()

	os.wait()

	f=open('anchorPoint'+str(serial),'w')
        f.write("optimize")
	f.close()
	line = "optimize"

if line.find("optimize") != -1:
	pid = os.spawnvpe(os.P_NOWAIT, 'python',[ 'python', './optimize.py',str(serial)],os.environ)
	f = open("./../webserverScripts/pid"+str(serial),'a')
	f.write (' '+str(pid)+' ')
	f.close()

	os.wait()

	#Then remove the status file....
	os.system("rm -rf ./../status"+str(serial))
	os.system("rm -rf ./anchor"+str(serial))
	os.system("rm -rf ./restore"+str(serial))


